<template>
  <a-upload
    name="avatar"
    listType="picture-card"
    class="avatar-uploader"
    :showUploadList="false"
    :beforeUpload="beforeUpload"
    :customRequest="uploadImage"
  >
    <a-avatar
      class="avatar"
      :size="128"
      :src="userInfo ? userInfo.userFace : '/avatar2.jpg'"
    />
    <div class="ant-upload-text">
      编辑头像
    </div>
  </a-upload>
</template>
<script>
import Cookies from "js-cookie";
import { upload } from "@/api/My";

export default {
  inject: ["reload"],
  data() {
    return {
      userInfo: {}
    };
  },
  created() {
    this.getUserInfo();
  },
  methods: {
    getUserInfo() {
      this.userInfo = JSON.parse(Cookies.get("userInfo"));
    },
    uploadImage(options) {
      const formData = new FormData();
      formData.append("file", options.file);

      upload(formData).then(response => {
        let data = response.data;
        if (data.flag) {
          console.log("回调");
          let url = data.data;
          console.log("url", url);
          //修改cookie中userInfo的头像信息
          this.userInfo.userFace = url;
          Cookies.set("userInfo", JSON.stringify(this.userInfo));
          this.reload(); //刷新页面
        }
      });
    },

    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 2MB!");
      }
      return isJpgOrPng && isLt2M;
    }
  }
};
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
